package com.spzx.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.cart.api.RemoteCartService;
import com.spzx.cart.api.domain.CartInfo;
import com.spzx.common.core.constant.HttpStatus;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.rabbit.service.RabbitService;
import com.spzx.order.api.domain.OrderInfo;
import com.spzx.order.api.domain.OrderItem;
import com.spzx.order.domain.OrderLog;
import com.spzx.order.domain.vo.OrderForm;
import com.spzx.order.domain.vo.TradeVo;
import com.spzx.order.mapper.OrderInfoMapper;
import com.spzx.order.mapper.OrderItemMapper;
import com.spzx.order.mapper.OrderLogMapper;
import com.spzx.order.service.IOrderInfoService;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.domain.vo.SkuPrice;
import com.spzx.user.api.RemoteUserAddressService;
import com.spzx.user.domain.UserAddress;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService {
    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private OrderLogMapper orderLogMapper;

    @Autowired
    private RemoteCartService remoteCartService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RemoteProductService remoteProductService;

    @Autowired
    private RemoteUserAddressService remoteUserAddressService;

    @Autowired
    RabbitService rabbitService; //来自于公共模块：spzx-common-rabbit

    /**
     * 查询订单列表
     *
     * @param orderInfo 订单
     * @return 订单
     */
    @Override
    public List<OrderInfo> selectOrderInfoList(OrderInfo orderInfo) {
        return orderInfoMapper.selectOrderInfoList(orderInfo);
    }

    /**
     * 查询订单
     *
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public OrderInfo selectOrderInfoById(Long id) {
        OrderInfo orderInfo = orderInfoMapper.selectById(id);
        List<OrderItem> orderItemList = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, id));
        orderInfo.setOrderItemList(orderItemList);
        return orderInfo;
    }

    @Override
    public TradeVo orderTradeData() {

        //先罗列出来TradeVo里需要封装的数据

        TradeVo tradeVo = new TradeVo();

        BigDecimal totalAmount = new BigDecimal(0);

        ArrayList<OrderItem> orderItemList = new ArrayList<>();

        String tradeNo = "";

        // 获取当前登录用户的id

        Long userId = SecurityContextHolder.getUserId();

        //调用远程的cart微服务的方法来获取选中的商品
        R<List<CartInfo>> cartInfoListR = remoteCartService.getCartCheckedList(userId, SecurityConstants.INNER);

        if (cartInfoListR.getCode() == HttpStatus.ERROR){
            throw new ServiceException(cartInfoListR.getMsg());
        }

        List<CartInfo> cartInfoList = cartInfoListR.getData();

        //将CartInfo中的属性复制到OrderItem中
        for (CartInfo cartInfo : cartInfoList) {
            OrderItem orderItem = new OrderItem();
            BeanUtils.copyProperties(cartInfo,orderItem);
            orderItemList.add(orderItem);
        }

        tradeVo.setOrderItemList(orderItemList);

        //获取总金额

        for (OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }

        tradeVo.setTotalAmount(totalAmount);

        //最后获取交易流水号
        //1.构建流水号Key
        String userTradeKey = "user:tradeNo:" + userId;
        //2.构建流水号value
        tradeNo = UUID.randomUUID().toString().replaceAll("-", "");
        //3.将流水号存入Redis 暂存5分钟
        redisTemplate.opsForValue().set(userTradeKey, tradeNo, 5, TimeUnit.MINUTES);

        tradeVo.setTradeNo(tradeNo);

        return tradeVo;
    }


    @Override
    public Long submitOrder(OrderForm orderForm) {

        //开发步骤
        /*
        1.验证用户是否重复提交订单
        2.验证表单参数是否为空
        3.校验价格变化
        4.校验库存并锁定库存 TODO
        5.保存订单(订单表,订单项表,订单日志表)
        6.删除购物车中选中的商品
         */

        /*
        第一步开发思路:
            1.首先是否是重复提交,这个前端可以管控,如果用户点了提交按钮一次,这个按钮就会失效,所以做到了仅提交一次
            2.这个方法有效但不保险,所以后端也可以做一下管控
            3.首先用户在去结算到支付之间,是生成了一个持续5分钟的一个交易流水号存在了缓存中的
            4.所以说当调用到这个接口第一次的时候,就需要校验流水号是否存在,存在就删掉流水号,再次调用接口就会判断没有流水号,之间报错
         */

        //获取用户id,然后获取到流水号的key
        Long userId = SecurityContextHolder.getUserId();
        String userTradeKey = "user:tradeNo:" + userId;
        //查询流水号是否存在
        //走到这说明是第一次创建订单,校验通过了,直接删除缓存中的流水号
        //由于查询流水号和删除流水号的操作要保证原子性,所以直接用Lua脚本实现
        String scriptText = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                "then\n" +
                "    return redis.call(\"del\",KEYS[1])\n" +
                "else\n" +
                "    return 0\n" +
                "end";
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        redisScript.setScriptText(scriptText);
        redisScript.setResultType(Long.class);
        Long flag = (Long) redisTemplate.execute(redisScript, Arrays.asList(userTradeKey), orderForm.getTradeNo());

        //如果值为0,说明没删除成功,说明是第二次提交订单
        //直接抛异常
        if (flag == 0) {
            throw new ServiceException("请勿重复提交订单，请尝试重试");
        }

        //第二部开发: 验证提交过来的表单参数是否为空
        if (CollectionUtils.isEmpty(orderForm.getOrderItemList())){
            //走到这说明表单项为空,直接抛异常
            throw new ServiceException("请求不合法");
        }

        //第三步开发: 校验价格是否变化
        //首先先调用远程接口拿到最新的售价
        //获取到商品的id集合
        ArrayList<Long> skuIdList = new ArrayList<>();
        for (OrderItem orderItem : orderForm.getOrderItemList()) {
            skuIdList.add(orderItem.getSkuId());

        }
        R<HashMap<Long, SkuPrice>> skuPriceListR = remoteProductService.getSkuPriceList(skuIdList, SecurityConstants.INNER);

        if (skuPriceListR.getCode() == 500){
            throw new ServiceException(skuPriceListR.getMsg());
        }

        HashMap<Long, SkuPrice> skuPriceHashMap = skuPriceListR.getData();

        //走到这已经拿到了从数据库里查出来的最新的商品价格数据了,这时候和表单中传过来的数据做比较判断
        //发现了商品价格变化就抛出异常提示用户重新返回购物车页面提交订单

        StringBuilder checkResult = new StringBuilder();

        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        for (OrderItem orderItem : orderItemList) {
            if (orderItem.getSkuPrice().compareTo(skuPriceHashMap.get(orderItem.getSkuId()).getSalePrice()) != 0){
                checkResult.append(orderItem.getSkuName() + "的价格发生了变化; ");
            }
        }

        if (StringUtils.hasText(checkResult.toString())){

            //走到这说明有商品的价格发生了变化,这时要更新购物车价格并告诉用户
            remoteCartService.updateCartPrice(userId,SecurityConstants.INNER);

            throw new ServiceException(checkResult.toString() + "请返回购物车重新下单");

        }

        //第四步 校验库存锁定库存 TODO


        //第五步 保存订单
        Long orderId = null;

        try {
            orderId = saveOrder(orderForm);
        } catch (Exception e) {
            throw new ServiceException("保存订单异常");
        }

        //第六步 删除购物车选中的商品
        remoteCartService.deleteCartCheckedList(userId,SecurityConstants.INNER);


        return orderId;
    }

    @Transactional
    public Long saveOrder(OrderForm orderForm) {

        Long userId = SecurityContextHolder.getUserId();
        String userName = SecurityContextHolder.getUserName();

        //保存订单对象
        OrderInfo orderInfo = new OrderInfo();

        orderInfo.setOrderNo(orderForm.getTradeNo());
        orderInfo.setUserId(userId);
        orderInfo.setNickName(userName);
        orderInfo.setRemark(orderForm.getRemark());
        UserAddress userAddress = remoteUserAddressService.getUserAddress(orderForm.getUserAddressId(), SecurityConstants.INNER).getData();
        orderInfo.setReceiverName(userAddress.getName());
        orderInfo.setReceiverPhone(userAddress.getPhone());
        orderInfo.setReceiverTagName(userAddress.getTagName());
        orderInfo.setReceiverProvince(userAddress.getProvinceCode());
        orderInfo.setReceiverCity(userAddress.getCityCode());
        orderInfo.setReceiverDistrict(userAddress.getDistrictCode());
        orderInfo.setReceiverAddress(userAddress.getFullAddress());

        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        orderInfo.setTotalAmount(totalAmount);
        orderInfo.setCouponAmount(new BigDecimal(0));
        orderInfo.setOriginalTotalAmount(totalAmount);
        orderInfo.setFeightFee(orderForm.getFeightFee());
        //OrderInfo类的orderStatus属性的类型改为Integer
        orderInfo.setOrderStatus(0);

        orderInfoMapper.insert(orderInfo);

        //保存订单项目

        for (OrderItem orderItem : orderItemList) {
            orderItem.setOrderId(orderInfo.getId());
            orderItemMapper.insert(orderItem);
        }




        //保存订单日志
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderInfo.getId());
        orderLog.setProcessStatus(0);
        orderLog.setNote("提交订单");
        orderLog.setOperateUser("用户");
        orderLogMapper.insert(orderLog);


        return orderInfo.getId();
    }
}